package com.tim.app.ui.fragment.home;

import android.content.Intent;
import android.content.res.Configuration;
import android.media.Image;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.application.library.base.BaseFragment;
import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.HorizontalDividerItemDecoration;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.application.library.widget.refresh.PtrClassicFrameLayout;
import com.application.library.widget.refresh.PtrDefaultHandler;
import com.application.library.widget.refresh.PtrFrameLayout;
import com.application.library.widget.refresh.PtrHandler;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.cache.CacheMode;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MsgService;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.db.dao.DaoFactory;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.entry.Dynamic;
import com.tim.app.server.entry.SelectInfo;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.DynamicListResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.message.MessageActivity;
import com.tim.app.ui.activity.selected.PublishDynamicActivity;
import com.tim.app.ui.adapter.someone_homepage.HomepageDynamicAdapter;
import com.tim.app.ui.popup.SelectDynamicPop;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

import java.util.ArrayList;
import java.util.List;

import static com.tim.app.constant.AppKey.DYNAMIC_TYPE_ALL;
import static com.tim.app.constant.AppKey.DYNAMIC_TYPE_FOLLOWER;
import static com.tim.app.constant.AppKey.TYPE_COMMENT;

/**
 * 动态页面
 */
public class HomeDynamicFragment extends BaseFragment implements View.OnClickListener, PtrHandler, LoadMoreHandler, BaseRecyclerAdapter.OnItemClickListener {

    public static final String TAG = "HomeDynamicFragment";
    private View rootView;
    private PtrClassicFrameLayout refresh_layout;
    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrvArticle;
    private EmptyLayout emptyLayout;
    private HomepageDynamicAdapter adapter;
    private List<Dynamic> dataList;

    private int pageNum = 1;
    private int type = DYNAMIC_TYPE_ALL;

    private View llSelectDynamic;

    private ImageView ivNoticeIcon;
    private ImageView ivPublishDynamic;
    private ImageView ivSelectDynamic;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == rootView) {
            rootView = inflater.inflate(R.layout.fragment_dynamic, container, false);

            refresh_layout = (PtrClassicFrameLayout) rootView.findViewById(R.id.refresh_layout);

            load_more = (LoadMoreRecycleViewContainer) rootView.findViewById(R.id.load_more);
            wrvArticle = (WrapRecyclerView) rootView.findViewById(R.id.wrvArticle);
            wrvArticle.setOverScrollMode(View.OVER_SCROLL_NEVER);

            refresh_layout.disableWhenHorizontalMove(true);
            refresh_layout.setPtrHandler(this);
            load_more.useDefaultFooter(View.GONE);
            load_more.setAutoLoadMore(true);
            load_more.setLoadMoreHandler(this);

            llSelectDynamic = rootView.findViewById(R.id.llSelectDynamic);
            ivNoticeIcon = (ImageView) rootView.findViewById(R.id.ivNoticeIcon);
            ivPublishDynamic = (ImageView) rootView.findViewById(R.id.ivPublishDynamic);
            ivSelectDynamic = (ImageView) rootView.findViewById(R.id.ivSelectDynamic);

            llSelectDynamic.setOnClickListener(this);
            ivNoticeIcon.setOnClickListener(this);
            ivPublishDynamic.setOnClickListener(this);
            emptyLayout = new EmptyLayout(getActivity(), refresh_layout);
            emptyLayout.showLoading();

            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            wrvArticle.setLayoutManager(layoutManager);
            wrvArticle.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(getResources().getColor(R.color.view_background_color)).size((int) getResources().getDimension(R.dimen.splitLineHeight)).build());
            dataList = new ArrayList<>();
            adapter = new HomepageDynamicAdapter(getActivity(), dataList);
            wrvArticle.setAdapter(adapter);
            adapter.setOnItemClickListener(this);
            emptyLayout.setErrorButtonClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    emptyLayout.showLoading();
                    initData(type);
                }
            });
            if (UserManager.ins().isLogin()) {
                emptyLayout.setEmptyDrawable(R.drawable.ic_empty_dynamic);
                emptyLayout.setEmptyText("暂时还没有好友动态", "");
                ivSelectDynamic.setVisibility(View.VISIBLE);
            } else {
                emptyLayout.setEmptyButtonShow(true);
                emptyLayout.setEmptyButtonText("注册/登录");
                emptyLayout.setEmptyDrawable(R.drawable.ic_empty_dynamic);
                emptyLayout.setEmptyText("暂未登录，无法查看好友动态", "");
                emptyLayout.setEmptyButtonClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ViewGT.gotoLoginActivity(getActivity());
                    }
                });
                ivSelectDynamic.setVisibility(View.GONE);
            }
            initData(type);
        } else {
            if (refresh_layout != null) {
                refresh_layout.refreshComplete();
            }
        }
        EventManager.ins().registListener(EventTag.ON_DYNAMIC_ALL, eventListener);
        EventManager.ins().registListener(EventTag.ON_DYNAMIC_FRIEDN, eventListener);
        EventManager.ins().registListener(EventTag.ON_DYNAMIC_DELETED, eventListener);
        EventManager.ins().registListener(EventTag.ON_DYNAMIC_ADD, eventListener);
        EventManager.ins().registListener(EventTag.ON_MESSAGE_STATED_CHANGED, eventListener);
        EventManager.ins().registListener(EventTag.DO_REFRESH_DYNAMIC, eventListener);
        EventManager.ins().registListener(EventTag.ACCOUNT_LOGIN, eventListener);
        EventManager.ins().registListener(EventTag.ACCOUNT_LOGOUT, eventListener);
        showUnreadMesageView();
        return rootView;
    }

    /**
     * 消息的view
     */
    private void showUnreadMesageView() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final int unReadMessageTotalCount = NIMClient.getService(MsgService.class).getTotalUnreadCount();
                final int unReadNoticeCount = DaoFactory.getNoticeDao().getUnReadMessageCount();
                if (unReadMessageTotalCount > 0 || unReadNoticeCount > 0 || UserManager.ins().getUnreadOfficialMessageCount() > 0) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ivNoticeIcon.setSelected(true);
                        }
                    });
                }
            }
        }).start();
    }

    public int getDynamicType() {
        return type;
    }

    @Override
    public void onItemClick(View view, int position, long id) {
        if (null == dataList || position > dataList.size() - 1)
            return;
        SelectInfo info = dataList.get(position);
        ViewGT.gotoDetailActivity(getActivity(), info);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivPublishDynamic:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(getActivity());
                    return;
                }
                Intent intent = new Intent(getActivity(), PublishDynamicActivity.class);
                startActivity(intent);
                break;
            case R.id.llSelectDynamic:
                if (UserManager.ins().isLogin()) {
                    SelectDynamicPop selectPicPop = new SelectDynamicPop(getContext(), getDynamicType());
                    selectPicPop.show(getActivity().getWindow().getDecorView());
                }
                break;
            case R.id.ivNoticeIcon:
                if (UserManager.ins().isLogin()) {
                    MessageActivity.start(getActivity());
                } else {
                    ViewGT.gotoLoginActivity(getActivity());
                }
                break;
        }
    }

    /**
     * 初始化数据
     *
     * @param type
     */
    private void initData(int type) {
        pageNum = 1;
        if (DYNAMIC_TYPE_ALL == type) {
            API_Found.ins().getDynamicList(TAG, AppKey.DYNAMIC_TYPE_ALL, pageNum, AppKey.PAGE_SIZE, CacheMode.REQUEST_FAILED_READ_CACHE, refreshCallback);
        } else if (DYNAMIC_TYPE_FOLLOWER == type) {
            if (UserManager.ins().isLogin()) {
                API_Found.ins().getDynamicList(TAG, AppKey.DYNAMIC_TYPE_FOLLOWER, pageNum, AppKey.PAGE_SIZE, CacheMode.REQUEST_FAILED_READ_CACHE, refreshCallback);
            } else {
                emptyLayout.showEmpty();
            }
        }
    }

    /**
     * 加载跟股东数据
     *
     * @param type
     */
    private void getMoreData(int type) {
        if (DYNAMIC_TYPE_ALL == type) {
            API_Found.ins().getDynamicList(TAG, AppKey.DYNAMIC_TYPE_ALL, pageNum + 1, AppKey.PAGE_SIZE, CacheMode.REQUEST_FAILED_READ_CACHE, moreCallback);
        } else if (DYNAMIC_TYPE_FOLLOWER == type) {
            API_Found.ins().getDynamicList(TAG, AppKey.DYNAMIC_TYPE_FOLLOWER, pageNum + 1, AppKey.PAGE_SIZE, CacheMode.REQUEST_FAILED_READ_CACHE, moreCallback);
        }
    }

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            refresh_layout.refreshComplete();
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                if (dataList != null) {
                    dataList.clear();
                }
                DynamicListResult result = new Gson().fromJson(resultValue, DynamicListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                    }
                    pageNum = result.getRes().getArraylist().getCurrentPageNo();
                    if (pageNum != result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(true, true);
                    } else {
                        load_more.loadMoreFinish(true, false);
                    }
                }

                if (dataList == null || dataList.size() == 0) {
                    emptyLayout.showEmpty();
                } else {
                    emptyLayout.showContent();
                }
            } else {
                emptyLayout.showEmptyOrError(errCode);
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                DynamicListResult result = new Gson().fromJson(resultValue, DynamicListResult.class);
                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                    }
                    pageNum = result.getRes().getArraylist().getCurrentPageNo();
                    if (pageNum != result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(true, true);
                    } else {
                        load_more.loadMoreFinish(true, false);
                    }
                }

            } else {
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.ON_DYNAMIC_ALL:
                    type = DYNAMIC_TYPE_ALL;
                    initData(type);
                    break;
                case EventTag.ON_DYNAMIC_FRIEDN:
                    type = DYNAMIC_TYPE_FOLLOWER;
                    initData(type);
                    break;
                case EventTag.ON_DYNAMIC_DELETED:
                    String deleteId = (String) dataobj;
                    for (int i = 0; i < dataList.size(); i++) {
                        if (dataList.get(i).getId().equals(deleteId)) {
                            dataList.remove(i);
                            adapter.notifyDataSetChanged();
                        }
                    }
                    break;
                case EventTag.ON_DYNAMIC_ADD:
                    initData(type);
                    break;
                case EventTag.ON_MESSAGE_STATED_CHANGED:
                    boolean isShow = (boolean) dataobj;
                    ivNoticeIcon.setSelected(isShow);
                    break;
                case EventTag.DO_REFRESH_DYNAMIC:
                    wrvArticle.scrollToPosition(0);
                    refresh_layout.autoRefresh();
                    break;
                case EventTag.ACCOUNT_LOGIN:
                    showUnreadMesageView();
                    initData(type);
                    ivSelectDynamic.setVisibility(View.VISIBLE);
                    break;
                case EventTag.ACCOUNT_LOGOUT:
                    ivNoticeIcon.setSelected(false);
                    ivSelectDynamic.setVisibility(View.GONE);
                    initData(type);
                    break;
            }

        }
    };

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != rootView && null != rootView.getParent()) {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
        EventManager.ins().removeListener(EventTag.ON_DYNAMIC_ALL, eventListener);
        EventManager.ins().removeListener(EventTag.ON_DYNAMIC_FRIEDN, eventListener);
        EventManager.ins().removeListener(EventTag.ON_DYNAMIC_DELETED, eventListener);
        EventManager.ins().removeListener(EventTag.ON_DYNAMIC_ADD, eventListener);
        EventManager.ins().removeListener(EventTag.ON_MESSAGE_STATED_CHANGED, eventListener);
        EventManager.ins().removeListener(EventTag.DO_REFRESH_DYNAMIC, eventListener);
        EventManager.ins().removeListener(EventTag.ACCOUNT_LOGIN, eventListener);
        EventManager.ins().removeListener(EventTag.ACCOUNT_LOGOUT, eventListener);
    }


    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, wrvArticle, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        initData(type);
    }

    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        getMoreData(type);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


}
